package com.ebupt.migu.music.iop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.iop.mapper.*;
import com.ebupt.migu.music.iop.pojo.*;
import com.ebupt.migu.music.iop.pojo.dto.IopTagDto;
import com.ebupt.migu.music.iop.pojo.vo.TagDetailVo;
import com.ebupt.migu.music.iop.pojo.vo.TagTreeVo;
import com.ebupt.migu.music.iop.service.IopTagService;
import com.ebupt.migu.music.system.entity.SysUser;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * iop标签
 * @author tz
 */
@Slf4j
@Service
public class IopTagServiceImpl extends ServiceImpl<IopTagInfoMapper, IopTagInfo> implements IopTagService {

    @Resource
    private IopTagCollectMapper iopTagCollectMapper;
    @Resource
    private IopTagUserMapper iopTagUserMapper;
    @Autowired
    private HbaseTemplate hbaseTemplate;
    @Value("${hbase.table}")
    private String TABLE;

    @Override
    public ResultObject tagsTree() {
        List<IopTagInfo> iopTagInfos = baseMapper.selectAll();
        //按标签等级分组
        Map<Integer, List<IopTagInfo>> collect = iopTagInfos.stream().collect(Collectors.groupingBy(IopTagInfo::getTagLevel));
        //获取标签树，从一级标签开始
        List<TagTreeVo> vos = recurTree(collect, collect.get(1), 1);
        return new ResultObject().success("ok",vos);
    }

    @Override
    public ResultObject getIopTag(Integer id) {
        IopTagInfo info = baseMapper.selectById(id);
        TagDetailVo vo = new TagDetailVo();
        BeanUtils.copyProperties(info, vo);
        Optional.ofNullable(vo.getTagUserGroup()).ifPresent(e -> {
            RowCount c = hbaseTemplate.get(TABLE, e, new RowCountMapper());
            BeanUtils.copyProperties(c, vo);
            vo.setTagUserGroupName(c.getTagName());
        });
        return new ResultObject().success("ok",vo);
    }

    @Override
    public ResultObject updateIopTag(IopTagDto dto) {
        IopTagInfo info = baseMapper.selectById(dto.getId());
        info.setTagUserGroup(dto.getTagUserGroup());
        baseMapper.updateById(info);
        return new ResultObject().success("ok");
    }

    @Override
    public ResultObject collectTag(SysUser user, String tagId) {
        IopTagCollect info = iopTagCollectMapper.selectByUser(user);
        if (Optional.ofNullable(info).isPresent()) {
            List<String> list = Lists.newArrayList(info.getCollectList().split(","));
            list.add(tagId);
            info.setCollectList(String.join(",",list));
            iopTagCollectMapper.updateById(info);
        } else {
            IopTagCollect collect = new IopTagCollect();
            collect.setUserId(user.getId());
            collect.setUserName(user.getUserName());
            collect.setCollectList(tagId);
            iopTagCollectMapper.insert(collect);
        }
        return new ResultObject().success("ok");
    }

    @Override
    public ResultObject cancelCollect(SysUser user, String tagId) {
        IopTagCollect info = iopTagCollectMapper.selectByUser(user);
        Optional.ofNullable(info).ifPresent(e -> {
            List<String> list = Lists.newArrayList(e.getCollectList().split(","));
            list.remove(tagId);
            e.setCollectList(String.join(",",list));
            iopTagCollectMapper.updateById(e);
        });
        return new ResultObject().success("ok");
    }

    @Override
    public ResultObject qryCollect(SysUser user) {
        IopTagCollect info = iopTagCollectMapper.selectByUser(user);
        if (Optional.ofNullable(info).isPresent()) {
            List<String> list = Lists.newArrayList(info.getCollectList().split(","));
            List<IopTagInfo> iopTagInfos = baseMapper.selectBatchIds(list);
            List<TagTreeVo> vos = iopTagInfos.stream().map(e -> {
                TagTreeVo vo = new TagTreeVo();
                BeanUtils.copyProperties(e, vo);
                Optional.ofNullable(e.getTagUserGroup()).ifPresent(f -> {
                    RowCount c = hbaseTemplate.get(TABLE, f, new RowCountMapper());
                    vo.setTagUserGroupName(c.getTagName());
                    vo.setUserSize(Integer.valueOf(c.getPhoneCount()));
                });
                return vo;
            }).collect(Collectors.toList());
            return new ResultObject().success("ok",vos);
        } else {
            return new ResultObject().success("ok",new ArrayList<>());
        }
    }

    @Override
    public ResultObject qryTagUserList() {
        List<IopTagUser> iopTagUsers = iopTagUserMapper.selectAll();
        return new ResultObject().success("ok",iopTagUsers);
    }

    @Override
    public ResultObject allCount(List<String> ids) {
        return new ResultObject().success("ok",ids.stream().map(i ->
                hbaseTemplate.get(TABLE, i, new RowCountMapper())).mapToInt(count ->
                Integer.parseInt(count.getPhoneCount())).sum());
    }

    /**
     * 递归获取树结构
     */
    private List<TagTreeVo> recurTree(Map<Integer, List<IopTagInfo>> map,List<IopTagInfo> list,int i){
        if (i > map.size()){
            return new ArrayList<>();
        }
        return list.stream().map(e -> {
            TagTreeVo vo = new TagTreeVo();
            BeanUtils.copyProperties(e, vo);
            List<IopTagInfo> v2 = map.get(i + 1).stream().filter(f ->
                    f.getTagParent().equals(e.getId())).collect(Collectors.toList());
            vo.setChild(recurTree(map,v2,i));
            vo.setTagCaliber(StringUtils.isEmpty(e.getTagCaliber()) ? "暂无" : e.getTagCaliber());
            vo.setUpdateCycle(StringUtils.isEmpty(e.getTagCaliber()) ? "无更新" : e.getTagCaliber());
            vo.setCount(v2.size());
            Optional.ofNullable(e.getTagUserGroup()).ifPresent(f -> {
                RowCount c = hbaseTemplate.get(TABLE, f, new RowCountMapper());
                vo.setTagUserGroupName(c.getTagName());
                vo.setUserSize(Integer.valueOf(c.getPhoneCount()));
            });
            return vo;
        }).collect(Collectors.toList());
    }

}
